var Content=React.createClass({
	helpList:[
		{
			title:'轻社区介绍',
			icon:'fa-comment',
			content: i18next.t('console.home.prompt1')
		},
		{
			title:'大屏幕展示',
			icon:'fa-comment',
			content: i18next.t('console.home.prompt2')
		},
		{
			title:'大众点评介绍',
			icon:'fa-comment',
			content: i18next.t('console.home.prompt3')
		}
	],
	getInitialState:function(){
		moment.locale('en', {
		    relativeTime : {
				past: i18next.t('time.past'),
		        m:  i18next.t('time.minute'),
		        mm: i18next.t('time.minutes'),
		        h:  i18next.t('time.hour'),
		        hh: i18next.t('time.hours'),
		        d:  i18next.t('time.day'),
		        dd: i18next.t('time.days'),
		        M:  i18next.t('time.month'),
		        MM: i18next.t('time.months'),
		        y:  i18next.t('time.year'),
		        yy: i18next.t('time.years')
		    },
			meridiem : function (hour, minute, isLowercase) {
				if (hour < 9) {
					return i18next.t('variable.morning');
				} else if (hour < 11) {
					return i18next.t('variable.forenoon');
				} else if (hour < 13) {
					return i18next.t('variable.noon');
				} else if (hour < 18) {
					return i18next.t('variable.afternoon');
				} else {
					return i18next.t('variable.evening');
				}
			}
		});

		return {
			contentData:[],
			layout:localStorage.getItem('wall_list_layout') || 'cards'
		}
	},
	componentDidMount:function(){
		var options=this.props.options;

		options.contentData(this,true)
	},
	changeLayout:function(layout){
		localStorage.setItem('wall_list_layout',layout);

		this.setState({
			layout:layout
		})
	},
	render:function(){
		var self=this,
			options=this.props.options,
			socialAccount=options.socialAccount,
			userAccount=options.userAccount,
			contentData=this.state.contentData,
			layout=this.state.layout,
			Plan=typeof plan!='undefined'?plan:null,
			maxWallNumber=(Plan && Plan.features) ? Plan.features.max_wall_count : 1;

		return (
			<div>
				<section className="content-header">
					<h1>{i18next.t("dashboard.welcome", {time: moment().format('a'), name: userAccount.name})}<small>{socialAccount.name}</small><a style={{display:'none'}} className="pull-right" href="#">更多帮助信息</a></h1>
				</section>
				<div className="content helping-content">
					<HelpingContent helpList={this.helpList} />
				</div>
				<section className="content-header">
					<h1>{i18next.t('console.home.prompt4')}<small>{socialAccount.name}</small>
						<div className="box-tools pull-right origin-btn-group">
							<div className="btn-group">
								<button type="button" className={"btn btn-default btn-sm"+(layout=='cards'?' active':'')} onClick={function(){self.changeLayout('cards')}} title= {i18next.t('console.card_layout')} ><i className="fa fa-th"></i></button>
								<button type="button" className={"btn btn-default btn-sm"+(layout=='rows'?' active':'')} onClick={function(){self.changeLayout('rows')}} title= {i18next.t('console.list_view')} ><i className="fa fa-list"></i></button>
							</div>
							{contentData.length < maxWallNumber?<a href="/walls/create" className="btn btn-default btn-sm" style={{marginLeft:'10px'}} title= {i18next.t('console.build_billboard')}><i className="fa fa-plus"></i></a>:null}
						</div>
					</h1>
					
				</section>
				<div className="content">
					{(function(){
						switch(layout){
							case 'rows':
								return <RowsLayout data={contentData} />;
							case 'cards':
							default:
								return <CardsLayout data={contentData} />;

						}
					})()}
		        </div>
	        </div>
		)
	}
});

/*wall集成此类*/
var WallItemMixin=function(){
	return {
		getInitialState:function(){
			var data=this.props.data,
				startDate=data.realtime.start_timestamp,
				endDate=data.realtime.stop_timestamp;

			this.startDate=startDate;
			this.endDate=endDate;

			return {
				hover:false,
				isRealtimeOpen:startDate&&endDate,
				realtimeRemaining:null
			}
		},
		componentDidMount:function(){
			this.realtimeInterval()
		},
		realtimeSetting:function(e){
			if(!this.state.isRealtimeOpen){
				ReactDOM.render(<RealTimeSetting title={i18next.t('console.open_real_time_setting')} callback={this.setRealtime} cancelCallback={this.closeRealTimeSetting} data={this.props.data} />,document.getElementById('modal'))
			}else{

			}
		},
		closeRealTimeSetting:function(){
			this.refs.checkbox.checked=false
		},
		setRealtime:function(param,callback){
			var self=this;
			console.log(param);
			$.ajax({
				type:'get',
				url:'/purchase?'+$.param(param),
				dataType:'json',
				success:function(data){
					if(data.success){
						self.setState({
							isRealtimeOpen:true
						},function(){
							self.startDate=param.start_date;
							self.endDate=param.end_date;

							self.realtimeInterval()
						});
						callback(true,data.data)
					}else{
						callback(false,data.error)
					}
				},
				error:function(){
					callback(false,'购买失败，请检查网络连接')
				}
			})
		},
		componentWillUnmount:function(){
			this.clearRealtimeInterval()
		},
		getRemaining:function(){
			var startDate=this.startDate,
				endDate=this.endDate;

			if(new Date().getTime() < new Date(startDate).getTime()){
				return 1
			}

			if((new Date(startDate).getTime() < new Date(endDate).getTime()) && (new Date().getTime() < new Date(endDate).getTime())){
				return 2
			}

			return 0
			
		},
		realtimeInterval:function(){
			
			if(this.state.isRealtimeOpen){
				var self=this;

				this.clearRealtimeInterval();

				this.timer=setInterval(function(){
					var remaining=self.getRemaining();
					if(!remaining){
						self.setState({
							isRealtimeOpen:false
						});
						self.clearRealtimeInterval();
						return
					}

					var	now=moment(),
						targetDate=moment(remaining==1?self.startDate:self.endDate),
						calc = {
						years: function() {
							return targetDate.diff( now, 'years');
						},
						months: function() {
							targetDate.subtract( calc.years(), 'years' );
							return targetDate.diff( now, 'months');
						},
						days: function() {
							targetDate.subtract( calc.months(), 'months' );
							return targetDate.diff( now, 'days' );
						},
						hours: function() {
							targetDate.subtract( calc.days(), 'days' );
							return targetDate.diff( now, 'hours' );
						},
						minutes: function() {
							targetDate.subtract( calc.hours(), 'hours' );
							return targetDate.diff( now, 'minutes' );
						},
						seconds: function() {
							targetDate.subtract( calc.minutes(), 'minutes' );
							return targetDate.diff( now, 'seconds' );
						}
					};

					self.setState({
						realtimeRemaining:{
							years: calc.years(),
							months: calc.months(),
							days: calc.days(),
							hours: calc.hours(),
							minutes: calc.minutes(),
							seconds: calc.seconds()
						}
					})
				},1000)
			}
		},
		clearRealtimeInterval:function(){
			if(this.timer){
				clearInterval(this.timer);
				this.timer=null
			}
		}
	}
};

/*列表布局*/
var RowsLayout=React.createClass({
	render:function(){
		var data=this.props.data,
			Plan=typeof plan!='undefined'?plan:null,
			maxWallNumber=(Plan && Plan.features) ? Plan.features.max_wall_count : 1;

		return (
			<div className="row">
				<div className="col-md-12">
					{data.map(function(i,index){
						return <WallRow key={index} data={i} />
					})}
				</div>
			</div>
		)
	}
});

var WallRow=React.createClass({
	mixins:[WallItemMixin()],
	render:function(){
		var data=this.props.data,
			Plan=typeof plan!='undefined'?plan:null,
			hasAnalytics=(Plan && Plan.features) ? Plan.features.screen_impression_analytics : false,
			isRealtimeOpen=this.state.isRealtimeOpen,
			realtimeRemaining=this.state.realtimeRemaining,
			remaining=this.getRemaining(),
			Plan=typeof plan!='undefined'?plan:null,
			realtimePrice=(Plan && Plan.productions) ? Plan.productions.realtime_update.price : -1;;

		return (
			<div className="col-xs-12">
				<div className="box box-solid wall-item-row">
					<div className="wall-item-row-bg" style={{backgroundImage:'url('+data.background+'?imageView2/3/w/350)'}}></div>
					<div className="wall-item-row-content">
						<h3>
							{data.logo?<div className="wall-logo" style={{backgroundImage:'url('+data.logo+')'}}></div>:null}
							<a href={"/wall/"+data.id} target="_blank">{data.name}</a>
							{<WallRowClipboard data={data.id} />}
							{data.qr_code?<div className="wall-qrcode"><i className="fa fa-qrcode"><QrcodeTooltip data={data.qr_code} /></i></div>:null}	
						</h3>
						<p className="box-desc">{data.description}</p>
						<p className="box-date">{i18next.t('console.update')} {data.last_updated_date ? (function(){try{return moment(data.last_updated_date).fromNow()}catch(err){ return i18next.t('time.minute_inside')}})() : '--'}</p>
						<div className="box-footer">
							{realtimePrice>=0?<span title= {i18next.t('console.open_real_time')} className={"box-setting wall-row-realtime"+(isRealtimeOpen && realtimeRemaining?' text-yellow':'')} onClick={this.realtimeSetting}>
								<i className="fa fa-clock-o"></i>
								{isRealtimeOpen && realtimeRemaining?realtimeRemaining.days+"天"+realtimeRemaining.hours+"时"+realtimeRemaining.minutes+"分"+realtimeRemaining.seconds+i18next.t('time.seconds_later')+(remaining==1? i18next.t('time.start'): i18next.t('time.end')):""}
							</span>:null}
							<div className="wall-item-row-tools">
								<a title= {i18next.t('console.open_billboard')} href={"/wall/"+data.id} target="_blank" className="box-setting">
									<i className="fa fa-play-circle"></i>
								</a>
								{/*<a title= {i18next.t('console.open_calendar')} href={"/calendar?id="+data.id} target="_blank" className="box-setting">
									<i className="fa fa-calendar"></i>
								</a>*/}
								<a title= {i18next.t('console.picture_manage')} href={"/walls/"+data.id+"/photos"} className="box-setting">
									<i className="fa fa-image"></i>
								</a>
								<a title= {i18next.t('console.user_manage')} href={"/walls/"+data.id+"/fans"} className="box-setting">
									<i className="fa fa-user"></i>
								</a>
								{hasAnalytics?<a style={{display:'inline'}} title="查看报表" href={"/walls/" + data.id + "/reports"} className="box-setting">
									<i className="fa fa-bar-chart"></i>
								</a>:null}
								<a title= {i18next.t('console.setting_billboard')} href={"/walls/" + data.id + '/edit'} className="box-setting">
									<i className="fa fa-gear"></i>
								</a>
							</div>
						</div>
					</div>
				</div>
			</div>
		)
	}
});

var WallRowClipboard=React.createClass({
	refresh:function(){
		var data=this.props.data;

		$('#clipboard'+data+' .tooltip-inner').text(i18next.t('console.copy_url'))
	},
	render:function(){
		var data=this.props.data;

		return (
			<span onMouseLeave={this.refresh} id={'clipboard'+data} data-clipboard-text={location.origin+"/wall/"+data} className="wall-clipboard pull-right">
				<i className="fa fa-clipboard"></i>
				<TooltipBottom />
			</span>
		)
	}
});

/*提示窗*/
var QrcodeTooltip=React.createClass({
	render:function(){
		var data=this.props.data;

		return (
			<div className="tooltip left">
				<div className="tooltip-arrow"></div>
				<div className="tooltip-inner"><img src={data} width="100" height="100" /></div>
			</div>
		)
	}
});

var TooltipBottom=React.createClass({
	render:function(){
	
		return (
			<div className="tooltip bottom">
				<div className="tooltip-arrow"></div>
				<div className="tooltip-inner">{i18next.t('console.copy_url')}</div>
			</div>
		)
	}
});

/*卡片布局*/
var CardsLayout=React.createClass({
	render:function(){
		var data=this.props.data,
			Plan=typeof plan!='undefined'?plan:null,
			maxWallNumber=(Plan && Plan.features) ? Plan.features.max_wall_count : 1;

		return (
			<div className="row">
				<div className="col-md-12">
					{data.map(function(i,index){
						return <WallCard key={index} data={i} />
					})}
					{(data.length < maxWallNumber)?<div className="wall_item wall_add col-lg-3 col-md-4 col-sm-6 col-xs-12">
						<a href="/walls/create" className="box box-solid bg-light-blue">
							<div className="box-body">
								<div className="icon-plus"></div>
								<h4>{i18next.t('console.build_billboard')}</h4>
							</div>
						</a>
					</div>:null}
				</div>
			</div>
		)
	}
});

var WallCard=React.createClass({
	mixins:[WallItemMixin()],
	mouseIn:function(){
		this.setState({
			hover:true
		})
	},
	mouseOut:function(){
		this.setState({
			hover:false
		})
	},render:function(){
		var data=this.props.data,
			isRealtimeOpen=this.state.isRealtimeOpen,
			realtimeRemaining=this.state.realtimeRemaining,
			remaining=this.getRemaining(),
			Plan=typeof plan!='undefined'?plan:null,
			hasAnalytics=(Plan && Plan.features) ? Plan.features.screen_impression_analytics : false,
			realtimePrice=(Plan && Plan.productions) ? Plan.productions.realtime_update.price : -1;

		return (
			<div className={"wall_item col-lg-3 col-md-4 col-sm-6 col-xs-12 "+(this.state.hover?'wall_item_hover':'')} onMouseOver={this.mouseIn} onMouseLeave={this.mouseOut} >
				<div className="box box-solid front" style={data.background_color?{backgroundColor:unescape(data.background_color)}:{backgroundImage:'url('+data.background+'?imageView2/3/w/350)'}}>
					<div className="box-header">
						<h4>{data.logo?<div className="wall-logo" style={{backgroundImage:'url('+data.logo+')'}}></div>:null}<a href={"/wall/"+data.id} target="_blank">{data.name}</a></h4>
					</div>
					<div className="box-body" style={{color:unescape(data.font_color)}}>
						<p>{data.description || '暂无描述'}</p>
						<p className="box-date">{i18next.t('console.update')} {data.last_updated_date ? (function(){try{return moment(data.last_updated_date).fromNow()}catch(err){ return i18next.t('time.minute_inside') }})() : '--'}</p>
						<div className="clearfix"></div>
					</div>
					<div className="box-footer with-border">
						<span>{i18next.t('console.photo_number')} : {data.photo_count || '--'}</span>
						<span>{i18next.t('console.user_number')} : {data.user_count || '--'}</span>
					</div>
				</div>
				<div className="box box-solid back">
					<div className="box-header with-border">
						{realtimePrice>=0?<h4><span>{isRealtimeOpen && realtimeRemaining?realtimeRemaining.days+"天"+realtimeRemaining.hours+"时"+realtimeRemaining.minutes+"分"+realtimeRemaining.seconds+i18next.t('time.seconds_later')+(remaining==1? i18next.t('time.start'): i18next.t('time.end')): i18next.t('console.open_real_time')}</span>
							<div className="setrealtime-botton"><input ref="checkbox" className="weui_switch" type="checkbox" onChange={this.realtimeSetting} checked={isRealtimeOpen} disabled={isRealtimeOpen} /></div>
						</h4>:<h4>
							<span>{data.name}</span>
						</h4>}
					</div>
					<div className="box-body" style={{color:unescape(data.font_color)}}>
						<div className="wall_item_body">
							<div className="wall_tools">
								<a href={"/wall/"+data.id} target="_blank" className="box-setting pull-left" title= {i18next.t('console.open_billboard')}><i className="fa fa-play-circle"></i></a>
								<a href={"/walls/" + data.id + '/edit'} className="box-setting pull-right" title= {i18next.t('console.setting_billboard')}><i className="fa fa-gear"></i></a>
								{hasAnalytics?<a style={{display:'inline'}} href={"/walls/" + data.id + "/reports"} className="box-setting pull-right" title="查看报表"><i className="fa fa-bar-chart"></i></a>:''}
								{/*<a href={"/calendar?id="+data.id} target="_blank" className="box-setting pull-right" title= {i18next.t('console.open_calendar')}><i className="fa fa-calendar"></i></a>*/}
							</div>
							<div className="wall-clipboard-box">
								<div className="input-group">
									<input className="form-control" type="text" readOnly value={location.protocol+"//"+location.host+"/wall/"+data.id} onClick={function(e){$(e.target).select()}} onFocus={function(e){$(e.target).select()}} />
									<div className="input-group-addon"><i className="fa fa-link"></i></div>
								</div>
								<span className="help-block">{i18next.t('console.text')}</span>
							</div>
							<div className="clearfix"></div>
						</div>
					</div>
					<div className="box-footer with-border">
						<a href={"/walls/"+data.id+"/fans"} className="btn btn-flat btn-default">{i18next.t('console.user_manage')}</a>
						<a href={"/walls/"+data.id+"/photos"} className="btn btn-flat btn-primary">{i18next.t('console.picture_manage')}</a>
					</div>
				</div>
			</div>
		)
	}
});

/*警告信息*/
var Warning=React.createClass({
	render:function(){
		var title=this.props.title,
			content=this.props.content;

		return (
			<div>
				<div className="callout callout-info">
					<h4>{title}</h4>
					<p>{content}</p>
				</div>
				<div className="walllist-empty-icon text-center">
					<img className="img-responsive" src="/images/crossscreen.png" />
				</div>
			</div>
		)
	}
});

/*帮助信息*/
var HelpingContent=React.createClass({
	render:function(){
		var helpList=this.props.helpList;

		return (
			<div className="row">
		        <div className="col-md-12">
					{helpList.map(function(i,index){
						return <HelpingItem key={index} data={i} index={index} />
					})}
				</div>
			</div>
		)
	}
});

var HelpingItem=React.createClass({
	render:function(){
		var data=this.props.data,
			index=this.props.index;

		return (
			<div className={"col-md-4 col-xs-12 helping-item"+(index>0?" hidden-sm hidden-xs":"")}>
				<div className="box box-solid">
					<div className="box-body">
						<i className="fa fa-lightbulb-o bg-yellow"></i>
						<div className="helping-item-content">
							<p><strong>{i18next.t('console.tip')}：</strong>{data.content} <a style={{display:'none'}} href="javascript:void(0)">查看详情</a></p>
						</div>
					</div>
				</div>
			</div>
		)
	}
});


